/**
 * 前端服务管理器
 * 负责根据页面访问情况启动和停止后端服务
 */

class ServiceManager {
    constructor() {
        this.currentServices = new Set()
        this.idleTimer = null
        this.pageActiveTime = 0
        this.IDLE_TIMEOUT = 300000 // 5分钟无操作自动降级
        
        // 页面和服务的映射关系
        this.pageServiceMap = {
            '/': ['system_monitor'],                    // 仪表板页面
            '/monitor': ['realtime_monitor'],          // 系统监控页面
            '/docker': ['docker_service'],            // Docker管理页面
            '/network': ['network_monitor'],          // 网络配置页面
            '/experiment': ['system_monitor'],        // 实验管理页面
            '/settings': ['system_monitor']           // 设备设置页面
        }
        
        // 监听页面可见性变化
        this.setupVisibilityListener()
        
        // 监听用户活动
        this.setupActivityListener()
    }
    
    /**
     * 进入页面时启动相应服务
     */
    async enterPage(pagePath) {
        console.log(`[ServiceManager] 进入页面: ${pagePath}`)
        
        const requiredServices = this.pageServiceMap[pagePath] || []
        
        // 启动页面所需的服务
        for (const serviceName of requiredServices) {
            await this.startService(serviceName)
        }
        
        // 重置空闲定时器
        this.resetIdleTimer()
        
        // 记录页面激活时间
        this.pageActiveTime = Date.now()
    }
    
    /**
     * 离开页面时的处理
     */
    async leavePage(fromPath, toPath) {
        console.log(`[ServiceManager] 页面切换: ${fromPath} -> ${toPath}`)
        
        // 如果切换到相同服务需求的页面，不需要停止服务
        const fromServices = this.pageServiceMap[fromPath] || []
        const toServices = this.pageServiceMap[toPath] || []
        
        // 找出不再需要的服务
        const servicesToStop = fromServices.filter(service => 
            !toServices.includes(service)
        )
        
        // 延迟停止不再需要的服务（30秒后）
        if (servicesToStop.length > 0) {
            setTimeout(() => {
                servicesToStop.forEach(service => {
                    if (!this.isServiceNeededByCurrentPage(service)) {
                        this.stopService(service)
                    }
                })
            }, 30000) // 30秒延迟
        }
    }
    
    /**
     * 启动服务
     */
    async startService(serviceName, timeout = 300) {
        if (this.currentServices.has(serviceName)) {
            console.log(`[ServiceManager] 服务 ${serviceName} 已运行`)
            return true
        }
        
        try {
            console.log(`[ServiceManager] 启动服务: ${serviceName}`)
            const response = await fetch(`/api/system/services/start/${serviceName}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ timeout })
            })
            
            const result = await response.json()
            
            if (result.status === 'success') {
                this.currentServices.add(serviceName)
                console.log(`[ServiceManager] 服务 ${serviceName} 启动成功`)
                return true
            } else {
                console.warn(`[ServiceManager] 服务 ${serviceName} 启动失败:`, result.message)
                return false
            }
        } catch (error) {
            console.error(`[ServiceManager] 启动服务 ${serviceName} 时发生错误:`, error)
            return false
        }
    }
    
    /**
     * 停止服务
     */
    async stopService(serviceName) {
        if (!this.currentServices.has(serviceName)) {
            console.log(`[ServiceManager] 服务 ${serviceName} 未运行`)
            return true
        }
        
        try {
            console.log(`[ServiceManager] 停止服务: ${serviceName}`)
            const response = await fetch(`/api/system/services/stop/${serviceName}`, {
                method: 'POST'
            })
            
            const result = await response.json()
            
            if (result.status === 'success') {
                this.currentServices.delete(serviceName)
                console.log(`[ServiceManager] 服务 ${serviceName} 停止成功`)
                return true
            } else {
                console.warn(`[ServiceManager] 服务 ${serviceName} 停止失败:`, result.message)
                return false
            }
        } catch (error) {
            console.error(`[ServiceManager] 停止服务 ${serviceName} 时发生错误:`, error)
            return false
        }
    }
    
    /**
     * 获取当前活跃服务
     */
    async getActiveServices() {
        try {
            const response = await fetch('/api/system/services/status')
            const result = await response.json()
            
            if (result.status === 'success') {
                return result.data.active_services
            }
        } catch (error) {
            console.error('[ServiceManager] 获取服务状态失败:', error)
        }
        
        return []
    }
    
    /**
     * 初始化WebSocket连接
     */
    async initWebSocket() {
        try {
            console.log('[ServiceManager] 初始化WebSocket服务')
            const response = await fetch('/api/system/services/websocket/init', {
                method: 'POST'
            })
            
            const result = await response.json()
            
            if (result.status === 'success') {
                console.log('[ServiceManager] WebSocket服务初始化成功')
                return true
            } else {
                console.warn('[ServiceManager] WebSocket服务初始化失败:', result.message)
                return false
            }
        } catch (error) {
            console.error('[ServiceManager] 初始化WebSocket时发生错误:', error)
            return false
        }
    }
    
    /**
     * 检查服务是否被当前页面需要
     */
    isServiceNeededByCurrentPage(serviceName) {
        const currentPath = window.location.pathname
        const requiredServices = this.pageServiceMap[currentPath] || []
        return requiredServices.includes(serviceName)
    }
    
    /**
     * 设置页面可见性监听
     */
    setupVisibilityListener() {
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                console.log('[ServiceManager] 页面隐藏，开始降级服务')
                this.startIdleTimer(60000) // 页面隐藏后1分钟降级
            } else {
                console.log('[ServiceManager] 页面可见，恢复服务')
                this.resetIdleTimer()
                // 重新启动当前页面所需的服务
                const currentPath = window.location.pathname
                this.enterPage(currentPath)
            }
        })
    }
    
    /**
     * 设置用户活动监听
     */
    setupActivityListener() {
        const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart']
        
        const resetTimer = () => {
            this.resetIdleTimer()
        }
        
        events.forEach(event => {
            document.addEventListener(event, resetTimer, { passive: true })
        })
    }
    
    /**
     * 重置空闲定时器
     */
    resetIdleTimer() {
        if (this.idleTimer) {
            clearTimeout(this.idleTimer)
        }
        
        this.startIdleTimer(this.IDLE_TIMEOUT)
    }
    
    /**
     * 启动空闲定时器
     */
    startIdleTimer(timeout = this.IDLE_TIMEOUT) {
        this.idleTimer = setTimeout(() => {
            console.log('[ServiceManager] 检测到用户空闲，降级服务')
            this.degradeServices()
        }, timeout)
    }
    
    /**
     * 降级服务（停止非必要服务）
     */
    async degradeServices() {
        console.log('[ServiceManager] 开始降级服务')
        
        // 只保留基础的system_monitor服务，停止其他服务
        const servicesToKeep = ['system_monitor']
        
        for (const service of this.currentServices) {
            if (!servicesToKeep.includes(service)) {
                await this.stopService(service)
            }
        }
        
        console.log('[ServiceManager] 服务降级完成')
    }
    
    /**
     * 手动刷新所有服务
     */
    async refreshAllServices() {
        console.log('[ServiceManager] 手动刷新所有服务')
        
        // 停止所有当前服务
        const currentServices = Array.from(this.currentServices)
        for (const service of currentServices) {
            await this.stopService(service)
        }
        
        // 重新启动当前页面所需的服务
        const currentPath = window.location.pathname
        await this.enterPage(currentPath)
        
        console.log('[ServiceManager] 服务刷新完成')
    }
}

// 创建全局服务管理器实例
const serviceManager = new ServiceManager()

export default serviceManager